import json
import shutil
import os
from tqdm import tqdm
import datetime
import cv2
import torch
import matplotlib.pyplot as plt
# from .Post_processing import get_LBP, euclidean_distance

dist_thres = 100

save_path = '../../data/result'
query_dir = '../../data/test/query'
gallery_dir = '../../data/test/gallery'
json_path = '../submit_final.json'
json_LBP = dict()
with open(json_path, 'r') as fp:
    json_data = json.load(fp)
    ID = 0
    for query, gallerys in json_data.items():
        temp_save_path = save_path + '/' + str(ID)
        if not os.path.exists(temp_save_path):
            os.makedirs(temp_save_path)
        query_path = os.path.join(query_dir, query)
        shutil.copy(query_path, temp_save_path)
        os.rename(temp_save_path + '/' + query, temp_save_path + '/' + str(0) + '.jpg')

        # query_feat = get_LBP(cv2.imread(query_path))
        gallery_feat = []
        for idx, gallery in tqdm(enumerate(gallerys)):
            gallery_path = os.path.join(gallery_dir, gallery)
            shutil.copy(gallery_path, temp_save_path)
            os.rename(temp_save_path + '/' + gallery, temp_save_path + '/' + str(idx + 1) + '.jpg')

            # gallery_feat += [get_LBP(cv2.imread(gallery_path))]
        # gallery_feat = torch.cat(gallery_feat, dim=0)
        # distmat = euclidean_distance(query_feat, gallery_feat)[-1]
        # plt.plot(distmat)
        # plt.show()
        # # 根据距离阈值，对gallery重排序
        # filter_dist = distmat > dist_thres
        # good_list, bad_list = [], []
        # for i in range(len(gallerys)):
        #     if filter_dist[i]:
        #         good_list.append(gallerys[i])
        #     else:
        #         bad_list.append(gallerys[i])
        # gallerys = good_list + bad_list

        # # 重排序后的结果存在第二个文件夹
        # temp_save_path = save_path + '/' + str(ID) + '-rk'
        # for idx, gallery in enumerate(gallerys):
        #     gallery_path = os.path.join(gallery_dir, gallery)
        #     shutil.copy(gallery_path, temp_save_path)
        #     os.rename(temp_save_path + '/' + gallery, temp_save_path + '/' + str(idx + 1))
        ID += 1

        # json_LBP[query] = gallerys

# nowTime = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
# with open(os.path.join('./', 'LBP_result_{}.json'.format(nowTime)), 'w', encoding='utf-8') as fp:
#     json.dump(json_LBP, fp)
